package com.sdkj.controller.goods.applygoods;

import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.sdkj.controller.base.BaseController;
import com.sdkj.entity.Page;
import com.sdkj.entity.User;
import com.sdkj.util.AppUtil;
import com.sdkj.util.ObjectExcelView;
import com.sdkj.util.Const;
import com.sdkj.util.PageData;
import com.sdkj.util.Tools;
import com.sdkj.util.Jurisdiction;
import com.sdkj.util.UuidUtil;
import com.sdkj.service.goods.applygoods.ApplyGoodsDetailService;
import com.sdkj.service.goods.applygoods.ApplyGoodsService;
import com.sdkj.service.system.GoodTypeService;

/**
 * 类名称：ApplyGoodsController 创建人：FH 创建时间：2017-05-16
 */
@Controller
@RequestMapping(value = "/applygoods")
public class ApplyGoodsController extends BaseController {

	String menuUrl = "applygoods/list.do"; // 菜单地址(权限用)
	@Resource(name = "applygoodsService")
	private ApplyGoodsService applygoodsService;
	@Resource(name = "goodtypeService")
	private GoodTypeService goodTypeService;
	@Resource(name = "applygoodsdetailService")
	private ApplyGoodsDetailService applygoodsdetailService;

	/**
	 * 新增
	 */
	@RequestMapping(value = "/save")
	public ModelAndView save() throws Exception {
		logBefore(logger, "新增ApplyGoods");
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "add")) {
			return null;
		} // 校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		User user = getCurrentUser();
		String primaryKey = this.get32UUID();
		pd.put("apply_goods_id", primaryKey);// 主键
		pd.put("user_id", user.getUSER_ID());
		pd.put("company_id", user.getCompanyId());
		pd.put("department_id", user.getDepartmentId());
		pd.put("create_time", Tools.date2Str(new Date())); // 创建时间
		pd.put("apply_state", 0); // 审批状态
		pd.put("buy_state", 0); // 购买状态
		pd.put("putin_state", 0);// 入库状态
		applygoodsService.save(pd);

		mv.addObject("msg", "success");
		mv.setViewName("save_result");
		return mv;
	}

	/**
	 * 删除
	 */
	@RequestMapping(value = "/delete")
	public void delete(PrintWriter out) {
		logBefore(logger, "删除ApplyGoods");
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "del")) {
			return;
		} // 校验权限
		PageData pd = new PageData();
		try {
			pd = this.getPageData();
			applygoodsService.delete(pd);
			out.write("success");
			out.close();
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}

	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/edit")
	public ModelAndView edit() throws Exception {
		logBefore(logger, "修改ApplyGoods");
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {
			return null;
		} // 校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		applygoodsService.edit(pd);
		mv.addObject("msg", "success");
		mv.setViewName("save_result");
		return mv;
	}

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list")
	public ModelAndView list(Page page) {
		logBefore(logger, "列表ApplyGoods");
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "cha")) {
			return null;
		} // 校验权限
		int rank = 0;// 查看级别
		if (Jurisdiction.buttonJurisdiction(menuUrl, "cha_zj")) {
			rank=0;
		}
		if (Jurisdiction.buttonJurisdiction(menuUrl, "cha_dept")) {
			rank=1;
		}
		if (Jurisdiction.buttonJurisdiction(menuUrl, "cha_company")) {
			rank=2;
		}
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try {
			User user=getCurrentUser();
			pd = this.getPageData();
			pd.put("userId", user.getUSER_ID());
			pd.put("rank", rank);
			pd.put("deptId", user.getDepartmentId());
			pd.put("companyId", user.getCompanyId());
			String type = pd.getString("type");
			String keyword = pd.getString("keyword");
			String applyState = pd.getString("applyState");
			String lastLoginStart = pd.getString("lastLoginStart");
			String lastLoginEnd = pd.getString("lastLoginEnd");
			if (null != keyword && !"".equals(keyword)) {
				pd.put("keyword", keyword.trim());
			} else {
				pd.put("keyword", null);
			}
			if (null == lastLoginStart || "".equals(lastLoginStart)) {
				pd.put("lastLoginStart", null);
			}
			if (null == lastLoginEnd || "".equals(lastLoginEnd)) {
				pd.put("lastLoginEnd", null);
			}
			if ("-1".equals(applyState)) {
				pd.put("applyState", null);
			}
			pd.put("type", type);
			page.setPd(pd);
			List<PageData> varList = applygoodsService.list(page); // 列出ApplyGoods列表
			mv.setViewName("applygoods/apply/applygoods_list");
			mv.addObject("varList", varList);
			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}

	/**
	 * 列表
	 */
	@RequestMapping(value = "/listPutIn")
	public ModelAndView listPutIn(Page page) {
		logBefore(logger, "列表ApplyGoods");
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "cha")) {
			return null;
		} // 校验权限
		int rank = 0;// 查看级别
		if (Jurisdiction.buttonJurisdiction(menuUrl, "cha_zj")) {
			rank=0;
		}
		if (Jurisdiction.buttonJurisdiction(menuUrl, "cha_dept")) {
			rank=1;
		}
		if (Jurisdiction.buttonJurisdiction(menuUrl, "cha_company")) {
			rank=2;
		}
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try {
			User user=getCurrentUser();
			pd = this.getPageData();
			pd.put("userId", user.getUSER_ID());
			pd.put("rank", rank);
			pd.put("deptId", user.getDepartmentId());
			pd.put("companyId", user.getCompanyId());
			String keyword = pd.getString("keyword");
			String type = pd.getString("type");
			String lastLoginStart = pd.getString("lastLoginStart");
			String lastLoginEnd = pd.getString("lastLoginEnd");
			String putinState = pd.getString("putinState");
			if (null != keyword && !"".equals(keyword)) {
				pd.put("keyword", keyword.trim());
			} else {
				pd.put("keyword", null);
			}
			if (null == lastLoginStart || "".equals(lastLoginStart)) {
				pd.put("lastLoginStart", null);
			}
			if (null == lastLoginEnd || "".equals(lastLoginEnd)) {
				pd.put("lastLoginEnd", null);
			}
			if ("-1".equals(putinState)) {
				pd.put("putinState", null);
			}
			pd.put("type", type);
			pd.put("applyState", 1);// 审批同意
			pd.put("buyState", 2);// 采购完成
			page.setPd(pd);
			List<PageData> varList = applygoodsService.list(page); // 列出ApplyGoods列表
			mv.setViewName("applygoods/putin/putinwarehouse_list");
			mv.addObject("varList", varList);
			mv.addObject("pd", pd);
			mv.addObject(Const.SESSION_QX, this.getHC()); // 按钮权限
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}

	/**
	 * 去新增页面
	 */
	@RequestMapping(value = "/goAdd")
	public ModelAndView goAdd() {
		logBefore(logger, "去新增ApplyGoods页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();

		try {
			Page page = new Page();
			String type = pd.getString("type");
			PageData pdType = new PageData();
			pdType.put("type", type);
			pdType.put("use_state", "0");
			page.setPd(pdType);
			List<PageData> types = goodTypeService.list(page);
			mv.setViewName("applygoods/apply/applygoods_add");
			mv.addObject("types", types);
			mv.addObject("msg", "save");
			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}

	/**
	 * 去修改页面
	 */
	@RequestMapping(value = "/goEdit")
	public ModelAndView goEdit() {
		logBefore(logger, "去修改ApplyGoods页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			pd = applygoodsService.findById(pd); // 根据ID读取
			mv.setViewName("applygoods/apply/applygoods_edit");
			mv.addObject("msg", "edit");
			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}

	/**
	 * 去详情页面
	 */
	@RequestMapping(value = "/goDetail")
	public ModelAndView goDetail() {
		logBefore(logger, "去详情页面ApplyGoods页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			pd = applygoodsService.findById(pd); // 根据ID读取
			Page page = new Page();
			page.setPd(pd);
			List<PageData> detailList = applygoodsdetailService.list(page);
			mv.setViewName("applygoods/apply/applygoodsdetail");
			mv.addObject("msg", "detail");
			mv.addObject("pd", pd);
			mv.addObject("detailList", detailList);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}

	/**
	 * 批量删除
	 */
	@RequestMapping(value = "/deleteAll")
	@ResponseBody
	public Object deleteAll() {
		logBefore(logger, "批量删除ApplyGoods");
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "dell")) {
			return null;
		} // 校验权限
		PageData pd = new PageData();
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			pd = this.getPageData();
			List<PageData> pdList = new ArrayList<PageData>();
			String DATA_IDS = pd.getString("DATA_IDS");
			if (null != DATA_IDS && !"".equals(DATA_IDS)) {
				String ArrayDATA_IDS[] = DATA_IDS.split(",");
				applygoodsService.deleteAll(ArrayDATA_IDS);
				pd.put("msg", "ok");
			} else {
				pd.put("msg", "no");
			}
			pdList.add(pd);
			map.put("list", pdList);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			logAfter(logger);
		}
		return AppUtil.returnObject(pd, map);
	}

	/*
	 * 导出到excel
	 * 
	 * @return
	 */
	@RequestMapping(value = "/excel")
	public ModelAndView exportExcel() {
		logBefore(logger, "导出ApplyGoods到excel");
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "cha")) {
			return null;
		}
		ModelAndView mv = new ModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			Map<String, Object> dataMap = new HashMap<String, Object>();
			List<String> titles = new ArrayList<String>();
			titles.add(""); // 1
			titles.add(""); // 2
			titles.add(""); // 3
			titles.add(""); // 4
			titles.add(""); // 5
			titles.add(""); // 6
			dataMap.put("titles", titles);
			List<PageData> varOList = applygoodsService.listAll(pd);
			List<PageData> varList = new ArrayList<PageData>();
			for (int i = 0; i < varOList.size(); i++) {
				PageData vpd = new PageData();
				vpd.put("var1", varOList.get(i).getString("apply_goods_id")); // 1
				vpd.put("var2", varOList.get(i).getString("apply_section")); // 2
				vpd.put("var3", varOList.get(i).getString("apply_user_name")); // 3
				vpd.put("var4", varOList.get(i).getString("apply_kind_num")); // 4
				vpd.put("var5", varOList.get(i).getString("apply_acount_price")); // 5
				vpd.put("var6", varOList.get(i).getString("remark")); // 6
				varList.add(vpd);
			}
			dataMap.put("varList", varList);
			ObjectExcelView erv = new ObjectExcelView();
			mv = new ModelAndView(erv, dataMap);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}

	/* ===============================权限================================== */
	public Map<String, String> getHC() {
		Subject currentUser = SecurityUtils.getSubject(); // shiro管理的session
		Session session = currentUser.getSession();
		return (Map<String, String>) session.getAttribute(Const.SESSION_QX);
		// Map<String, String> a=new HashMap<String, String>();
		// a.put("add", "1");
		// a.put("del", "1");
		// return a;
	}

	/* ===============================权限================================== */

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(format,
				true));
	}
}
